// 医护端专用功能
let diagnosisData = [];
let patientsData = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeDoctorDashboard();
    setupCSVImport();
    loadSampleData(); // 加载示例数据用于演示
});

// 初始化医护工作台
function initializeDoctorDashboard() {
    // 设置底部导航
    setupBottomNavigation();
    
    // 初始化图表
    initializeCharts();
    
    // 设置患者搜索和筛选
    setupPatientFilters();
    
    console.log('医护工作台初始化完成');
}

// 底部导航功能
function setupBottomNavigation() {
    const navButtons = document.querySelectorAll('.nav-btn');
    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的active类
            navButtons.forEach(btn => btn.classList.remove('active'));
            // 为当前按钮添加active类
            this.classList.add('active');
        });
    });
}

// 显示指定区域
function showSection(sectionId) {
    // 隐藏所有区域
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => {
        section.classList.remove('active');
    });
    
    // 显示指定区域
    const targetSection = document.getElementById(sectionId);
    if (targetSection) {
        targetSection.classList.add('active');
    }
}

// 初始化图表
function initializeCharts() {
    // 疾病分布饼图
    const diseaseCtx = document.getElementById('diseaseChart').getContext('2d');
    window.diseaseChart = new Chart(diseaseCtx, {
        type: 'pie',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: [
                    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
                    '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // 症状频率柱状图
    const symptomCtx = document.getElementById('symptomChart').getContext('2d');
    window.symptomChart = new Chart(symptomCtx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: '症状出现次数',
                data: [],
                backgroundColor: '#36A2EB'
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // 严重程度分布图
    const severityCtx = document.getElementById('severityChart').getContext('2d');
    window.severityChart = new Chart(severityCtx, {
        type: 'doughnut',
        data: {
            labels: ['轻度', '中度', '重度'],
            datasets: [{
                data: [0, 0, 0],
                backgroundColor: ['#28a745', '#ffc107', '#dc3545']
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // 时间趋势折线图
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    window.trendChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '每日诊断数',
                data: [],
                borderColor: '#36A2EB',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                fill: true
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 设置患者筛选功能
function setupPatientFilters() {
    const searchInput = document.getElementById('patient-search');
    const severityFilter = document.getElementById('severity-filter');
    const urgencyFilter = document.getElementById('urgency-filter');
    
    if (searchInput) {
        searchInput.addEventListener('input', filterPatients);
    }
    if (severityFilter) {
        severityFilter.addEventListener('change', filterPatients);
    }
    if (urgencyFilter) {
        urgencyFilter.addEventListener('change', filterPatients);
    }
}

// 筛选患者
function filterPatients() {
    const searchTerm = document.getElementById('patient-search').value.toLowerCase();
    const severityFilter = document.getElementById('severity-filter').value;
    const urgencyFilter = document.getElementById('urgency-filter').value;
    
    const filteredPatients = patientsData.filter(patient => {
        const matchesSearch = !searchTerm || 
            patient.name.toLowerCase().includes(searchTerm) ||
            patient.symptoms.toLowerCase().includes(searchTerm);
        const matchesSeverity = !severityFilter || patient.severity === severityFilter;
        const matchesUrgency = !urgencyFilter || patient.urgency === urgencyFilter;
        
        return matchesSearch && matchesSeverity && matchesUrgency;
    });
    
    displayPatients(filteredPatients);
}

// 显示患者列表
function displayPatients(patients) {
    const tbody = document.getElementById('patients-tbody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    patients.forEach(patient => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${patient.id}</td>
            <td>${patient.name}</td>
            <td>${patient.age}</td>
            <td>${patient.symptoms}</td>
            <td>${patient.diagnosis}</td>
            <td><span class="severity-${patient.severity}">${patient.severity}</span></td>
            <td><span class="urgency-${patient.urgency}">${patient.urgency}</span></td>
            <td>${patient.date}</td>
            <td>
                <button class="btn-small" onclick="viewPatientDetails('${patient.id}')">查看</button>
                <button class="btn-small btn-danger" onclick="deletePatient('${patient.id}')">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 查看患者详情
function viewPatientDetails(patientId) {
    const patient = patientsData.find(p => p.id === patientId);
    if (patient) {
        alert(`患者详情：\n姓名：${patient.name}\n年龄：${patient.age}\n症状：${patient.symptoms}\n诊断：${patient.diagnosis}\n严重程度：${patient.severity}\n紧急程度：${patient.urgency}`);
    }
}

// 删除患者记录
function deletePatient(patientId) {
    if (confirm('确定要删除这条患者记录吗？')) {
        patientsData = patientsData.filter(p => p.id !== patientId);
        diagnosisData = diagnosisData.filter(d => d.patientId !== patientId);
        updateDashboard();
        filterPatients();
        showMessage('患者记录已删除', 'success');
    }
}

// 设置CSV导入功能
function setupCSVImport() {
    const fileInput = document.getElementById('csv-file');
    const uploadPlaceholder = document.getElementById('upload-placeholder');
    const uploadPreview = document.getElementById('upload-preview');
    
    if (uploadPlaceholder) {
        // 点击上传区域
        uploadPlaceholder.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 拖拽上传
        uploadPlaceholder.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadPlaceholder.style.borderColor = '#007bff';
        });
        
        uploadPlaceholder.addEventListener('dragleave', () => {
            uploadPlaceholder.style.borderColor = '#ddd';
        });
        
        uploadPlaceholder.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadPlaceholder.style.borderColor = '#ddd';
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });
    }
    
    if (fileInput) {
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileSelect(e.target.files[0]);
            }
        });
    }
}

// 处理文件选择
function handleFileSelect(file) {
    if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
        showMessage('请选择CSV格式的文件', 'error');
        return;
    }
    
    const uploadPlaceholder = document.getElementById('upload-placeholder');
    const uploadPreview = document.getElementById('upload-preview');
    const fileName = document.getElementById('file-name');
    
    if (uploadPlaceholder && uploadPreview && fileName) {
        uploadPlaceholder.style.display = 'none';
        uploadPreview.style.display = 'block';
        fileName.textContent = file.name;
        
        // 存储文件对象供后续处理
        window.selectedCSVFile = file;
    }
}

// 取消上传
function cancelUpload() {
    const fileInput = document.getElementById('csv-file');
    const uploadPlaceholder = document.getElementById('upload-placeholder');
    const uploadPreview = document.getElementById('upload-preview');
    
    if (fileInput && uploadPlaceholder && uploadPreview) {
        fileInput.value = '';
        uploadPlaceholder.style.display = 'block';
        uploadPreview.style.display = 'none';
        delete window.selectedCSVFile;
    }
}

// 处理CSV文件
function processCSV() {
    if (!window.selectedCSVFile) {
        showMessage('请先选择CSV文件', 'error');
        return;
    }
    
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const csvData = e.target.result;
            const parsedData = parseCSV(csvData);
            importCSVData(parsedData);
        } catch (error) {
            console.error('CSV处理错误:', error);
            showMessage('CSV文件处理失败: ' + error.message, 'error');
        }
    };
    
    reader.onerror = function() {
        showMessage('文件读取失败', 'error');
    };
    
    reader.readAsText(window.selectedCSVFile);
}

// 解析CSV数据
function parseCSV(csvText) {
    const lines = csvText.split('\n').filter(line => line.trim());
    if (lines.length < 2) {
        throw new Error('CSV文件内容为空或格式不正确');
    }
    
    const headers = lines[0].split(',').map(h => h.trim());
    const requiredHeaders = ['患者ID', '姓名', '年龄', '症状', '诊断结果', '严重程度', '紧急程度', '诊断时间'];
    
    // 检查表头
    for (const header of requiredHeaders) {
        if (!headers.includes(header)) {
            throw new Error(`缺少必要的表头: ${header}`);
        }
    }
    
    const data = [];
    const errors = [];
    
    for (let i = 1; i < lines.length; i++) {
        const values = lines[i].split(',').map(v => v.trim());
        if (values.length !== headers.length) {
            errors.push(`第${i+1}行列数不匹配`);
            continue;
        }
        
        const row = {};
        headers.forEach((header, index) => {
            row[header] = values[index];
        });
        
        // 数据验证
        if (!row['患者ID'] || !row['姓名'] || !row['症状']) {
            errors.push(`第${i+1}行数据不完整`);
            continue;
        }
        
        data.push(row);
    }
    
    return { data, errors };
}

// 导入CSV数据
function importCSVData(parsedData) {
    const { data, errors } = parsedData;
    
    // 转换数据格式
    const newPatients = data.map(row => ({
        id: row['患者ID'],
        name: row['姓名'],
        age: parseInt(row['年龄']) || 0,
        symptoms: row['症状'],
        diagnosis: row['诊断结果'],
        severity: row['严重程度'] || '未知',
        urgency: row['紧急程度'] || '非紧急',
        date: row['诊断时间'] || new Date().toLocaleString()
    }));
    
    // 添加到现有数据
    patientsData = [...patientsData, ...newPatients];
    
    // 更新界面
    updateDashboard();
    filterPatients();
    
    // 显示导入结果
    showImportResults(newPatients.length, errors);
    
    showMessage(`成功导入 ${newPatients.length} 条患者记录`, 'success');
}

// 显示导入结果
function showImportResults(successCount, errors) {
    const resultsDiv = document.getElementById('import-results');
    const summaryDiv = document.getElementById('import-summary');
    const errorsDiv = document.getElementById('import-errors');
    
    if (resultsDiv && summaryDiv && errorsDiv) {
        resultsDiv.style.display = 'block';
        
        summaryDiv.innerHTML = `
            <div class="import-success">
                <i class="fas fa-check-circle"></i>
                <span>成功导入 ${successCount} 条记录</span>
            </div>
        `;
        
        if (errors.length > 0) {
            errorsDiv.innerHTML = `
                <div class="import-errors">
                    <h4>导入错误 (${errors.length} 条)</h4>
                    <ul>
                        ${errors.map(error => `<li>${error}</li>`).join('')}
                    </ul>
                </div>
            `;
        } else {
            errorsDiv.innerHTML = '';
        }
    }
}

// 下载CSV模板
function downloadTemplate() {
    const template = `患者ID,姓名,年龄,症状,诊断结果,严重程度,紧急程度,诊断时间
P001,张三,35,头痛、发热,普通感冒,轻度,非紧急,2024-01-15 10:30
P002,李四,28,咳嗽、胸闷,支气管炎,中度,建议就医,2024-01-15 11:15
P003,王五,45,腹痛、腹泻,肠胃炎,轻度,非紧急,2024-01-15 14:20`;
    
    const blob = new Blob([template], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '患者诊断数据模板.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}

// 加载示例数据
function loadSampleData() {
    patientsData = [
        {
            id: 'P001',
            name: '张三',
            age: 35,
            symptoms: '头痛、发热、咳嗽',
            diagnosis: '普通感冒',
            severity: '轻度',
            urgency: '非紧急',
            date: '2024-01-15 10:30'
        },
        {
            id: 'P002',
            name: '李四',
            age: 28,
            symptoms: '咳嗽、胸闷、气短',
            diagnosis: '支气管炎',
            severity: '中度',
            urgency: '建议就医',
            date: '2024-01-15 11:15'
        },
        {
            id: 'P003',
            name: '王五',
            age: 45,
            symptoms: '腹痛、腹泻、恶心',
            diagnosis: '肠胃炎',
            severity: '轻度',
            urgency: '非紧急',
            date: '2024-01-15 14:20'
        }
    ];
    
    updateDashboard();
    filterPatients();
}

// 更新工作台数据
function updateDashboard() {
    // 更新统计数字
    document.getElementById('total-patients').textContent = patientsData.length;
    document.getElementById('total-diagnoses').textContent = patientsData.length;
    
    const urgentCases = patientsData.filter(p => p.urgency === '紧急').length;
    document.getElementById('urgent-cases').textContent = urgentCases;
    
    // 计算平均严重程度（数值化：轻度=1, 中度=2, 重度=3）
    const severityMap = { '轻度': 1, '中度': 2, '重度': 3, '未知': 1 };
    const avgSeverity = patientsData.length > 0 ? 
        (patientsData.reduce((sum, p) => sum + severityMap[p.severity], 0) / patientsData.length).toFixed(1) : 0;
    document.getElementById('avg-severity').textContent = avgSeverity;
    
    // 更新图表数据
    updateCharts();
}

// 更新图表数据
function updateCharts() {
    // 疾病分布
    const diseaseCounts = {};
    patientsData.forEach(patient => {
        diseaseCounts[patient.diagnosis] = (diseaseCounts[patient.diagnosis] || 0) + 1;
    });
    
    window.diseaseChart.data.labels = Object.keys(diseaseCounts);
    window.diseaseChart.data.datasets[0].data = Object.values(diseaseCounts);
    window.diseaseChart.update();
    
    // 症状频率（取前10个最常见症状）
    const symptomCounts = {};
    patientsData.forEach(patient => {
        const symptoms = patient.symptoms.split(/[、,，]/).map(s => s.trim());
        symptoms.forEach(symptom => {
            symptomCounts[symptom] = (symptomCounts[symptom] || 0) + 1;
        });
    });
    
    const topSymptoms = Object.entries(symptomCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10);
    
    window.symptomChart.data.labels = topSymptoms.map(s => s[0]);
    window.symptomChart.data.datasets[0].data = topSymptoms.map(s => s[1]);
    window.symptomChart.update();
    
    // 严重程度分布
    const severityCounts = { '轻度': 0, '中度': 0, '重度': 0 };
    patientsData.forEach(patient => {
        if (severityCounts.hasOwnProperty(patient.severity)) {
            severityCounts[patient.severity]++;
        }
    });
    
    window.severityChart.data.datasets[0].data = Object.values(severityCounts);
    window.severityChart.update();
    
    // 时间趋势（按日期分组）
    const dateCounts = {};
    patientsData.forEach(patient => {
        const date = patient.date.split(' ')[0]; // 只取日期部分
        dateCounts[date] = (dateCounts[date] || 0) + 1;
    });
    
    const sortedDates = Object.keys(dateCounts).sort();
    window.trendChart.data.labels = sortedDates;
    window.trendChart.data.datasets[0].data = sortedDates.map(date => dateCounts[date]);
    window.trendChart.update();
}

// 显示消息
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'exclamation-triangle' : 'info'}-circle"></i>
        <span>${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(messageDiv);
    
    // 自动移除
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}